package top.yiwyn.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.yiwyn.domain.Attachment;
import top.yiwyn.mapper.AttachmentMapper;
import top.yiwyn.util.AttachmentUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@RestController
@RequestMapping("/attachment")
public class AttachmentController {


    @Autowired
    AttachmentMapper attachmentMapper;

    /**
     * 文件上传直接把位置数据传入数据库
     *
     * @param uploadFile
     * @throws IOException
     */
    @PostMapping("/upload")
    public void upload(MultipartFile uploadFile) throws IOException {
        String path = System.getProperties().getProperty("user.home") + "/Desktop/upload/img/";
        File file1 = new File(path);
        if (!file1.exists()) {
            file1.mkdirs();
        }

        path += uploadFile.getOriginalFilename();
        uploadFile.transferTo(new File(path));
        attachmentMapper.insert(new Attachment(uploadFile.getOriginalFilename(), path, "img"));
    }


    /**
     * 文件下载
     *
     * @param id 需要下载的文件在数据库中的id
     * @return 返回的byte数据
     */
    @GetMapping("/download/{id}")
    public ResponseEntity<byte[]> download(HttpServletRequest request, @PathVariable("id") int id) throws UnsupportedEncodingException {
        System.out.println("文件下载");

        Attachment attachment = attachmentMapper.selectById(id);
//        创建下载地址
        String downloadPath = System.getProperties().getProperty("user.home") + "/Desktop/upload/img/";

        downloadPath += attachment.getFilename();

        File downloadFile = new File(downloadPath);

        HttpHeaders headers = new HttpHeaders();
        String fileName = attachment.getFilename();
        fileName = AttachmentUtil.setFileNameEncoder(request, fileName);
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            return new ResponseEntity<>(FileUtils.readFileToByteArray(downloadFile), headers, HttpStatus.OK);
        } catch (IOException e) {
            return new ResponseEntity<>(e.getMessage().getBytes(), HttpStatus.EXPECTATION_FAILED);
        }
    }

    /**
     * 查询数据库找到文件详细信息
     *
     * @param id
     * @return
     */
    @GetMapping("/getFileById/{id}")
    public Attachment getFile(@PathVariable("id") long id) {
        Attachment attachment = attachmentMapper.selectById(id);
        return attachment;
    }


}
